  <!--
* @description  : 询问笔录-展示物品信息
* @descriptionDetail: 询问笔录-展示物品信息
* @copyright    : 浙江烟草
* @author       : sy
* @create       : 2022-07-25 16:15:38
-->
<template>
  <view class="page">
    <view class="">
      <view style="margin: -6px -16px 0px -16px;">
        <u-gap :height="$theme.cm_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
      </view>
      <view class="m-flex-row">
        <view style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center;">
          <form-section style="width: inherit;" title="物品信息登记" iconColorClass="u-success"></form-section>
        </view>
        <view style="display: flex;flex-direction: row;align-items: center;">
          <u-icon
            name="baocun"
            color="primary"
            custom-prefix="csbi-icon"
            style="margin-right: 20rpx;"
            size="40"
            v-if="hasEdit"
            @click="saveGoods()"
          ></u-icon>
          <u-icon name="plus-circle" color="primary" size="40" v-if="hasAdd" @click="addGoods()"></u-icon>
        </view>
      </view>
      <!-- 先行物品登记清单 -->
      <view class="m-flex-row">
        <view class="u-font-28 total-tip">
          合计(查获金额)<text>
            {{ goodsTotalPrice }}
          </text>元
        </view>
        <view class="u-font-28 total-tip">
          合计(查获数量)<text>
            {{ goodsTotalNum }}
          </text>条
        </view>
      </view>
      <view class="m-flex-row">
        <view class="u-font-28 total-tip">
          合计(销售金额)<text>
            {{ goodsIllegalPrice }}
          </text>元
        </view>
        <view class="u-font-28 total-tip">
          合计(已销数量)<text>
            {{ goodsIllegalNum }}
          </text>条
        </view>
      </view>
      <view class="m-flex-row" style="padding: 20rpx 0;" v-if="showSearch">
        <u-search placeholder="请输入品规名称" :show-action="false" v-model="keyWord" @change="changeKeyWord">
        </u-search>
      </view>
      <view>
        <u-table font-size="26" style="border-left: none;">
          <u-tr class="u-tr border-left">
            <u-th width="12%" class="u-th">
              序号
            </u-th>
            <u-th width="40%" class="u-th">
              品种规格
            </u-th>
            <u-th width="20%" class="u-th">
              查获数量
            </u-th>
            <u-th width="28%" class="u-th">
              查获金额
            </u-th>
          </u-tr>
          <me-list
            :normalScrollView="true"
            :i="0"
            :height="getListHeight()"
            :loadData="loadData"
            ref="mescrollRef0"
          >
            <u-tr class="u-tr border-left" :class="[d.index == 0 ? 'border-Top' : '']" slot-scope="d">
              <u-td width="12%" class="u-td">
                {{ d.index + 1 }}
              </u-td>
              <u-td width="40%" class="u-td" style="color: #2979ff;">
                <text @click="itemDetail(d.data)">
                  {{ d.data.goodsName }}<!-- {{ d.data.spec ? d.data.spec : 'mm' }} -->
                </text>
              </u-td>
              <u-td width="20%" class="u-td">
                {{ d.data.qty || 0}}
              </u-td>
              <u-td width="28%" class="u-td">
                {{ d.data.amt || 0 }}
              </u-td>
            </u-tr>
          </me-list>
        </u-table>
      </view>
      <u-popup mode="bottom" height="46%" v-model="detailShow">
        <view class="content" style="padding: 40rpx;">
          <view style="position: fixed;top: 0;width: 100%;height: 30rpx;background-color: white;"></view>
          <view style="padding-bottom: 120rpx;">
            <u-row gutter="16">
              <u-col span="12">
                <text style="font-size: 30rpx;">
                  品牌品规: {{ detailData.goodsName }}
                </text>
              </u-col>
            </u-row>
            <u-row gutter="16">
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  查获数量(条): {{ detailData.qty }}
                </text>
              </u-col>
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  查获单价(元): {{ detailData.price }}
                </text>
              </u-col>
            </u-row>
            <u-row gutter="16">
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  批发价(元): {{ detailData.wholesalePrice }}
                </text>
              </u-col>
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  查获金额(元): {{ detailData.amt }}
                </text>
              </u-col>
            </u-row>
            <u-row gutter="16">
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  购进数量(条): {{ detailData.buyQty }}
                </text>
              </u-col>
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  购进单价(元): {{ detailData.buyPrice }}
                </text>
              </u-col>
            </u-row>
            <u-row gutter="16">
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  已销数量(条): {{ detailData.illegalQty }}
                </text>
              </u-col>
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  违法进货金额(元): {{ detailData.illegalbuyamt }}
                </text>
              </u-col>
            </u-row>
            <u-row gutter="16">
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  销售单价(元): {{ detailData.illegalPrice }}
                </text>
              </u-col>
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  销售金额(元): {{ detailData.illegalAmt }}
                </text>
              </u-col>
            </u-row>
            <u-row gutter="16">
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  获利: {{ detailData.reapProfit }}
                </text>
              </u-col>
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  单位: {{ detailData.unit }}
                </text>
              </u-col>
            </u-row>
            <u-row gutter="16">
              <u-col span="6">
                <text style="font-size: 24rpx;color: #666666;">
                  物品性质: {{ getDicName($u.dic.DIC_KEYS.GOODS_PROP_SUBTYPE, detailData.propSubtype) }}
                </text>
              </u-col>
            </u-row>
          </view>
          <view
            class="nwidth"
            style="padding: 10rpx;bottom: 20rpx;position: fixed;background-color: white;"
            v-show="hasAdd && !detailData.isSearched"
          >
            <u-button size="default" type="error" plain @click="handleDel">
              删除记录
            </u-button>
          </view>
        </view>
      </u-popup>
    </view>
  </view>
</template>

<script>
import mescrollList from "@/components/mescroll_list.vue";
import officeService from "@/service/case/office.service";
import FormSection from "@/components/form-section.vue";
import {
  DOC_STATUS,
} from "@/service/case/mapping/index.js";
export default {
  name: "GoodsListCom",
  components: {
    "me-list": mescrollList,
    FormSection,
  },
  props: {
    caseUuid: {
      type: String,
      default: "",
    },
    caseCode: {
      type: String,
      default: "",
    },
    widthP: {
      type: String,
      default: "100%",
    },
    hasEdit: {
      type: Boolean,
      default: false, // 是否可以编辑 默认不可以
    },
    hasAdd: {
      type: Boolean,
      default: false,
    },
    height: { // 不能设置100% 之类的。 设置具体 px 数值
      type: Number,
      default: 350, // 默认300 px
    },
    showSearch: {
      type: Boolean,
      default: false,
    },
    params: {
      type: Object,
      default: undefined,
    },
    handleStatus: { // 文书状态 空或未开始 涉案物品调用新接口
      type: String,
      default: undefined,
    },
  },
  data() {
    return {
      goodsList: [],
      keyWord: "",
      detailData: {},
      detailShow: false,
      nedLoadData: [],
    }
  },
  computed: {
    goodsTotalNum() { // 查获数量
      let num = 0;
      for (let i = 0; i < this.goodsList.length; i++) {
        try {
          num += Number(this.goodsList[i].qty ? this.goodsList[i].qty : 0);
        } catch (er) {
          console.log(er);
        }
        if (isNaN(num)) num = 0;
      }
      return num.toFixed(1);
    },
    goodsTotalPrice() { // 查获金额
      let totalPrice = 0;
      let realTxt = "0.00";
      for (let i = 0; i < this.goodsList.length; i++) {
        try {
          let qty = Number(this.goodsList[i].qty ? this.goodsList[i].qty : 0);
          let price = Number(this.goodsList[i].price ? this.goodsList[i].price : 0);
          totalPrice += qty * price;
          realTxt = Number(totalPrice).toFixed(2);
        } catch (er) {
          console.log(er);
          realTxt = "";
        }
      }
      return realTxt;
    },
    goodsIllegalNum() { // 已销数量
      let num = 0;
      for (let i = 0; i < this.goodsList.length; i++) {
        try {
          num += Number(this.goodsList[i].illegalQty ? this.goodsList[i].illegalQty : 0);
        } catch (er) {
          console.log(er);
        }
      }
      return num;
    },
    goodsIllegalPrice() { // 已销金额
      let totalPrice = 0;
      for (let i = 0; i < this.goodsList.length; i++) {
        try {
          let qty = Number(this.goodsList[i].illegalQty > 0 ? this.goodsList[i].illegalQty : 0);
          let price = Number(this.goodsList[i].illegalPrice ? this.goodsList[i].illegalPrice : 0);
          totalPrice += qty * price;
        } catch (er) {
          console.log(er);
        }
      }
      return totalPrice.toFixed(2);
    },
  },
  created() {},
  methods: {
    addGoods: function() {
      this.setRouteParam({
        goodsList: this.goodsList,
        clueList: this.params.orginalCaseClueList,
      });
      this.$u.route({
        url: "/pages/case/components/addRecordDocGoodsInfo",
        type: 'to',
        params: {
          caseUuid: this.caseUuid,
          caseCode: this.caseCode,
        },
      });
    },
    saveGoods() {
      this.$modal.showLoading("正在保存...");
      officeService.saveCaseGoodsPunishList(this.caseUuid, this.goodsList).then(res => {
        this.$modal.hideLoading();
        if (res.success) {
          this.$u.toast('保存成功');
          this.keyWord = "";
          this.$emit('saveRefresh', true);
          this.$refs['mescrollRef0'].resetList(true);
        } else {
          this.$modal.alert("保存失败:" + res.msg);
          this.$emit('saveRefresh', false);
        }
      }).catch(err => {
        this.$modal.hideLoading();
        this.$modal.alert("保存失败:" + err);
        this.$emit('saveRefresh', false);
      });
    },
    itemDetail(obj) {
      this.detailData = obj;
      this.detailShow = true;
    },
    handleDel() {
      this.$modal.alert("确定要移除该物品吗？", "提示", () => {
        this.delGoodsItem();
        this.detailShow = false;
      }, "确定", true);
    },
    delGoodsItem() {
      this.goodsList = this.goodsList.filter(itm => {
        if (this.detailData.goodsDtlUuid == itm.goodsDtlUuid) {
          return false;
        }
        return true;
      });
      this.$refs['mescrollRef0'].resetList(false);
      if (this.goodsList.length > 0) {
        this.saveGoods();
      } else {
        this.$u.toast('请至少输入一条物品信息');
      }
    },
    changeKeyWord(val) {
      this.$refs['mescrollRef0'].resetList(false);
    },
    refreshData(all) {
      this.keyWord = "";
      this.$refs['mescrollRef0'].resetList(true);
    },
    getDicName(keyword, code) {
      return this.$u.dic.getDicNameByKeyCode(keyword, code);
    },
    loadData(page, isNeedRefresh) {
      let interfaceFun = !this.handleStatus || this.handleStatus == DOC_STATUS.NOT_STAR ? 'caseGoodsDtlNewList' :
        'caseGoodsPunishList';
      return new Promise((resolve, reject) => {
        if (isNeedRefresh) {
          if (this.nedLoadData.length > 0 && (!this.handleStatus || this.handleStatus == DOC_STATUS.NOT_STAR)) {
            this.goodsList = [...this.$u.deepClone(this.nedLoadData),];
            let tmpList = [];
            if (this.$u.test.isEmpty(this.keyWord) || !this.showSearch) {
              tmpList = [...this.goodsList,];
            } else {
              tmpList = this.goodsList.filter(itm => {
                if (itm.goodsName.indexOf(this.keyWord) != -1) {
                  return true;
                }
                return false;
              });
            }
            if (tmpList.length > (page.size * (page.num - 1))) {
              let s = (page.size * (page.num - 1));
              let len = tmpList.length - s;
              if (len > page.size) {
                resolve({
                  data: tmpList.slice(s, s + page.size),
                  totalCount: tmpList.length,
                });
              } else {
                resolve({
                  data: tmpList.slice(s),
                  totalCount: tmpList.length,
                });
              }
            } else {
              resolve({
                data: [],
                totalCount: 0,
              });
            }
            return;
          }
          officeService[interfaceFun](this.caseUuid).then(res => {
            if (res.success) {
              this.goodsList = [...res.data,];
              let tmpList = [];
              if (this.$u.test.isEmpty(this.keyWord) || !this.showSearch) {
                tmpList = [...this.goodsList,];
              } else {
                tmpList = this.goodsList.filter(itm => {
                  if (itm.goodsName.indexOf(this.keyWord) != -1) {
                    return true;
                  }
                  return false;
                });
              }
              if (tmpList.length > (page.size * (page.num - 1))) {
                let s = (page.size * (page.num - 1));
                let len = tmpList.length - s;
                if (len > page.size) {
                  resolve({
                    data: tmpList.slice(s, s + page.size),
                    totalCount: tmpList.length,
                  });
                } else {
                  resolve({
                    data: tmpList.slice(s),
                    totalCount: tmpList.length,
                  });
                }
              } else {
                resolve({
                  data: [],
                  totalCount: 0,
                });
              }
            } else {
              this.$u.toast('查询失败');
              resolve({
                data: [],
                totalCount: 0,
              });
            }
          }).catch(err => {
            console.log(err);
            this.$u.toast('查询失败');
            resolve({
              data: [],
              totalCount: 0,
            });
          });
        } else {
          let tmpList = [];
          if (this.$u.test.isEmpty(this.keyWord) || !this.showSearch) {
            tmpList = [...this.goodsList,];
          } else {
            tmpList = this.goodsList.filter(itm => {
              if (itm.goodsName.indexOf(this.keyWord) != -1) {
                return true;
              }
              return false;
            });
          }
          if (tmpList.length > (page.size * (page.num - 1))) {
            let s = (page.size * (page.num - 1));
            let len = tmpList.length - s;
            if (len > page.size) {
              resolve({
                data: tmpList.slice(s, s + page.size),
                totalCount: tmpList.length,
              });
            } else {
              resolve({
                data: tmpList.slice(s),
                totalCount: tmpList.length,
              });
            }
          } else {
            resolve({
              data: [],
              totalCount: 0,
            });
          }
        }
      });
    },
    updateBackState(param) {
      if (param.data) {
        this.nedLoadData = [...param.data,];
        this.refreshData(false);
      }
    },
    getListHeight() {
      if (this.showSearch) {
        return (this.height - 76 - 50 - uni.upx2px(104)) + "px";
      } else {
        return (this.height - 76 - 50) + "px";
      }
    },
  },
}
</script>

<style lang="scss" scoped>
	@import "../case_common.scss";

	.total-tip {
		color: $u-tips-color;

		text {
			color: $u-type-warning;
			margin-left: 10rpx;
			margin-right: 10rpx;
		}
	}

	.flat-btn {
		position: fixed;
		bottom: 50rpx;
		margin: auto;
		left: 60rpx;
		right: 60rpx;
		z-index: 88;
	}

	.m-is-require {
		color: red;
		margin-left: -8px;
		font-size: 14px;
	}

	.border-left {
		border-left: 1px solid rgb(228, 231, 237);
	}

	.border-Top {
		border-top: 1px solid rgb(228, 231, 237);
	}

	.nwidth {
		width: calc(100% - 80rpx);
	}

	.u-td {
		white-space: nowrap;
		overflow: hidden;
	}
</style>
